package com.sumainfor.pc.epc.service.impl;

import com.sumainfor.common.config.LockUtil;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.HtmlUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.epc.dao.SettlementAuditMapper;
import com.sumainfor.pc.epc.dao.SettlementManageMapper;
import com.sumainfor.pc.epc.feign.GmioFeign;
import com.sumainfor.pc.epc.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.epc.service.SettlementAuditService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * @Author Eddy·Chen
 * @Email 835033913@qq.com
 * @Create 2019-04-09 18:37
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class SettlementAuditServiceImpl implements SettlementAuditService {

    @Autowired
    private SettlementAuditMapper auditMapper;

    @Autowired
    private SettlementManageMapper settlementManageMapper;

    @Autowired
    private GmioFeign gmioFeign;

    @Autowired
    private ZzuulFeign zzuulFeign;

    @Autowired
    private LockUtil lock;

    /**
     * 工程经理经理审核结算单打款操作
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult auditSettlement(Map<String, Object> params) {
        String remId = MapUtils.getString(params, "StaRemId");
        Integer state = MapUtils.getInteger(params, "State");
        ParamsCommon.commonUpdateParms(params, getClass());

        try {
            if (lock.getUntilHaveLock(remId)) {
                //查询打款记录
                Map<String, Object> remitInfo = auditMapper.getRemitByRemitId(remId);
                if (MapUtils.isEmpty(remitInfo)) {
                    return JsonResult.error("没有查询到打款记录");
                }
                String stasId = MapUtils.getString(remitInfo, "StasId");
                if (MapUtils.isEmpty(remitInfo)) {
                    return JsonResult.error("没有查询记录");
                }
                if (!MapUtils.getInteger(remitInfo, "RemState").equals(1)) {
                    return JsonResult.error("已经审核");
                }
                params.put("SysUserId", ContextUtils.getUserId());
                Map<String, Object> info = auditMapper.getInfoById(stasId);
                if (state.equals(3)) {
                    //打款成功
                    //打款的钱数量
                    BigDecimal price = ObjectUtil.convertBigDecimal(remitInfo.get("PayPrice"));
                    //计算已付金额
                    BigDecimal donePrice = ObjectUtil.convertBigDecimal(info.get("PaidPrice"));
                    donePrice = donePrice.add(price);
                    info.put("PaidPrice", donePrice);
                    //获取总金额
                    BigDecimal sumPrice = ObjectUtil.convertBigDecimal(info.get("CopeWithPrice"));
                    //计算待付金额
                    BigDecimal waitePrice = sumPrice.subtract(donePrice);
                    info.put("UnpaidPrice", waitePrice);
                    if (waitePrice.doubleValue() == 0) {
                        info.put("State", 1);
                    }

                    //更新详表数据信息
                    int row = settlementManageMapper.updateStaInfoData(info);
                    if (row <= 0) {
                        throw new TCException("审核失败 Info");
                    }


                    //计算主表金额数据
                    Map<String, Object> mainData = auditMapper.getMainById(MapUtils.getString(info, "StaId"));
                    //已付金额计算
                    BigDecimal mainDonePrice = ObjectUtil.convertBigDecimal(mainData.get("PaidPrices"));
                    mainDonePrice = mainDonePrice.add(price);
                    mainData.put("PaidPrices", mainDonePrice);
                    //获取总金额
                    BigDecimal mainSumPrice = ObjectUtil.convertBigDecimal(mainData.get("CopeWithPrices"));
                    //计算待付金额
                    BigDecimal mainWaitePrice = mainSumPrice.subtract(mainDonePrice);
                    mainData.put("UnpaidPrices", mainWaitePrice);
                    if (mainWaitePrice.doubleValue() == 0) {
                        mainData.put("StaType", 1);
                    }
                    //更新主表数据
                    ParamsCommon.commonUpdateParms(mainData, getClass());
                    row = settlementManageMapper.updateStaMainData(mainData);
                    if (row <= 0) {
                        throw new TCException("打款失败 80");
                    }
                }

                //更新结算单申请打款表
                remitInfo.put("RemState", state);
                remitInfo.put("SysUserId", ContextUtils.getUserId());
                remitInfo.put("AuditTime", new Date());
                remitInfo.put("AuditNotes", params.get("AuditNotes"));
                ParamsCommon.commonUpdateParms(remitInfo, getClass());
                int row = auditMapper.updateRemitData(remitInfo);
                if (row <= 0) {
                    throw new TCException("审核失败");
                }

                if (state.equals(3)) {
                    //已确认的情况下生成账单
                    //构建数据
                    CustomMap data = CustomMap.create()
                            .put("BiOutId", UUIDUtils.generatePrefixUuid("BIO_"));
                    data.put("BiOutName", "结算单");
                    data.put("Relation", remId);
                    data.put("IfTemporary", 0);
                    data.put("BiOutType", 2);
                    data.put("BiMoney", ObjectUtil.convertBigDecimal(remitInfo.get("PayPrice")));
                    data.put("StartTime", System.currentTimeMillis());
                    data.put("LateDay", ((Date) remitInfo.get("PayTime")).getTime());
                    data.put("StemType", 2);
                    data.put("CreateType", 2);
                    data.put("Create", ContextUtils.getUserId());
                    data.put("Applicant", remitInfo.get("insby"));
                    log.info("申请人的id: " + remitInfo.get("insby").toString());
                    data.put("Status", 1);

                    //获取归属公司
                    Map<String, Object> mainData = auditMapper.getMainById(MapUtils.getString(info, "StaId"));
                    String corId = auditMapper.getCorId(MapUtils.getString(mainData, "SourceId"));
                    data.put("CorId", corId);

                    //调用远程运营部服务
                    JsonResult result = gmioFeign.insertOutOrder(data);
                    if (result.isSuccess() == false) {
                        throw new TCException(result.getErrorMessage());
                    }
                }

                if (state.equals(2)) {
                    //被驳回
                    CustomMap data = CustomMap.create("MeType", 7)
                            .put("Title", "被驳回打款单")
                            .put("Content", HtmlUtil.stringToHTML("（" + MapUtils.getString(info, "SupId") + "）苏马供应商申请打款账单被驳回；", MapUtils.getString(info, "SupId"), Color.blue))
                            .put("by", ContextUtils.getUserId())
                            .put("IfJump", 1)
                            .put("Neturl", "/sys-engineeringmanager/settlement")
                            .put("term", 3);
                    zzuulFeign.AddMessage(data);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unLock(remId);
        }

        return JsonResult.actionSuccess();
    }

}
